import MapboxDraw, { MapboxDrawOptions } from '@ttfn/mapbox-gl-draw';
import { nanoid } from 'nanoid';
import { Mixin } from 'ts-mixer';
import { BaseKit } from '../base-kit';
import type { IDraw, IDrawOptions } from './types';
import '@ttfn/mapbox-gl-draw/dist/mapbox-gl-draw.css';

export class Draw extends Mixin(MapboxDraw, BaseKit) implements IDraw {
  private _id = nanoid();
  private _isShowUi?: boolean;
  displayControlsDefault: IDraw['displayControlsDefault'];
  constructor(options: IDrawOptions) {
    const { styles, map, ...restOptions } = options;
    const o: MapboxDrawOptions = { displayControlsDefault: true, ...restOptions };
    if (typeof styles === 'function') o.styles = styles(map);
    super({ ...o, name: 'draw', map });
    this.displayControlsDefault = o.displayControlsDefault;
    this.setStatus('enable');
  }

  private _setShowUi = (type: boolean | 'trigger') => {
    let node = document.getElementById(this._id);
    const show = type === 'trigger' ? !this._isShowUi : type;
    if (!node) {
      node = document.createElement('style');
      node.id = this._id;
      document.head.appendChild(node);
    }
    if (show) node.innerText = '';
    else node.innerText = `.${MapboxDraw.constants.classes.CONTROL} {display: none !important;}`;
    this._isShowUi = show;
    return !!show;
  };

  protected onStatusChange = () => {
    const enable = this.status === 'enable';
    this._setShowUi(enable);
    if (!enable) this.changeMode('simple_select');
  };
}
